<template>
<div class="container">
<!--  搜索-->
  <form action="/" class="search">
    <van-search
        class="searchS"
        v-model="value"
        :show-action = "value?true:false"
        placeholder="请输入搜索关键词"
        @cancel="onCancel"
        shape="round"
        background="#F00000"
        @input = "search"
    />
  </form>
  <NewCategory :sar="value" />

<!--  返回顶部-->
  <van-icon v-if="btnFlag" class="icon" name="back-top" size="50" @click="goTop" />
<!--  <NewList :sar="sar"/>-->
</div>
</template>

<script>
import { Toast } from 'vant';
import NewCategory from "@/views/Index/components/NewCategory";
import {mapState} from "vuex";

export default {
  name: "IndexPage",
  data() {
    return {
      value: '',
      sar:'',

      //判断返回顶部
      btnFlag:false,
    };
  },
  components:{
    NewCategory,

  },
  computed:{
    ...mapState(["Active"])
  },
  created() {
    this.$store.commit("changeActive", {Active: 0})
    localStorage.setItem("Active",JSON.stringify(0))
  },
  // window对象，所有浏览器都支持window对象。它表示浏览器窗口，监听滚动事件
  mounted () {
    window.addEventListener('scroll', this.scrollToTop)
  },
  destroyed () {
    window.removeEventListener('scroll', this.scrollToTop)
  },
  methods: {
    onCancel() {
      Toast('取消');
    },
    //实现首页搜索
    search(e){
      // console.log(e);
      this.sar = e;
      // console.log(this.sar)
    },
    //实现返回顶部
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑
    goTop () {
      const that = this
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5)
        document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
        if (that.scrollTop === 0) {
          clearInterval(timer)
        }
      }, 16)
    },

    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop () {
      const that = this
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      that.scrollTop = scrollTop
      if (that.scrollTop > 700) {
        that.btnFlag = true
      } else {
        that.btnFlag = false
      }
    }
  },
}
</script>

<style scoped lang="less">
.container{
  padding-bottom:60px;
}
.van-search__action{
  color:white;
}
.icon{
  position:fixed;
  bottom:60px;
  right:10px;
  opacity: 0.3;
  width:50px;
  height:50px;
  background-color:#F00000;
  color:white;
  border-radius:30%;
}
</style>